/*
 * Copyright 2012 Faculty of Informatics - Masaryk University.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.pa165.creatures.dao.impl;

import cz.muni.fi.pa165.creatures.dao.CreatureManagerDAO;
import cz.muni.fi.pa165.creatures.dao.exceptions.NonExistentEntityException;
import cz.muni.fi.pa165.creatures.model.Creature;
import cz.muni.fi.pa165.creatures.model.CreatureType;
import cz.muni.fi.pa165.creatures.model.Region;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;

/**
 * This class represents the implementation of all basic operations upon
 * {@link Creature} instances.
 * 
 * @author xmiklos1
 */
public class CreatureManagerDAOImpl implements CreatureManagerDAO {

    /**
     * Logger to log all caught exceptions.
     */
    private static final Logger logger = Logger.getLogger(CreatureManagerDAOImpl.class.getName());
    /**
     * Entity manager factory for getting entity managers.
     */
    private EntityManagerFactory entityManagerFactory = null;

    /**
     *
     * @param emf entity manager factory for subsequent getting of the
     * {@link EntityManager}s.
     */
    public CreatureManagerDAOImpl(EntityManagerFactory emf) {
        this.entityManagerFactory = emf;
    }

    /**
     * This method returns entity manager created by
     * {@link EntityManagerFactory} provided to class
     * {@link CreatureManagerDAOImpl} upon creation.
     *
     * @return entity manager created by
     * {@link CreatureManagerDAOImpl#entityManagerFactory}
     */
    public EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

    @Override
    public void create(Creature creature) {
        if (creature == null) {
            throw new IllegalArgumentException("Creature to create can not be a null object");
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();

            Region region = creature.getRegion();
            if (region != null) {
                region = em.getReference(region.getClass(), region.getId());
                creature.setRegion(region);
            }
            CreatureType creatureType = creature.getCreatureType();
            if (creatureType != null) {
                creatureType = em.getReference(creatureType.getClass(), creatureType.getId());
                creature.setCreatureType(creatureType);
            }
            em.persist(creature);
            if (region != null) {
                region.getCreatures().add(creature);
                em.merge(region);
            }
            if (creatureType != null) {
                creatureType.getCreatures().add(creature);
                em.merge(creatureType);
            }

            em.getTransaction().commit();
        } catch (EntityExistsException ex) {
            logger.log(Level.INFO, "Unable to store a creature {0}. Entity already exists.", creature.toString());
            em.getTransaction().rollback();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void remove(Creature creature) {
        if (creature == null) {
            throw new IllegalArgumentException("Creature to remove can not be a null object");
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Creature c;
            try {
                c = em.getReference(Creature.class, creature.getId());
            } catch (EntityNotFoundException ex) {
                throw new NonExistentEntityException();
            }
            em.remove(c);
            em.getTransaction().commit();
        } catch (NonExistentEntityException ex) {
            logger.log(Level.INFO, "Unable to remove a creature {0}", creature.toString());
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void update(Creature creature) {
//        try {
//            
//        } catch() {
//            
//        } finally {
//            if (em != null) {
//                em.close();
//            }
//        }
    }

    @Override
    public Creature get(Long id) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            return em.find(Creature.class, id);
        } catch (IllegalArgumentException ex) {
            logger.log(Level.INFO, "Unable to find entity, id ({0}) is null or not a valid primary key", id.toString());
            if (em != null) {
                em.close();
            }
            return null;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public int getCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Creature as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
